package com.ouwen.hotel.service;

import com.ouwen.hotel.po.HotelBooking;
import com.ouwen.hotel.repository.HotelRepository;
import org.apache.servicecomb.pack.omega.transaction.annotations.Compensable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.UUID;

/**
 * @author <a href="http://youngitman.tech">青年IT男</a>
 * @version v1.0.0
 * @className BookingServiceImpl
 * @description
 * @date 2019-12-16 15:50
 * @JunitTest: {@link  }
 **/
@Service
public class HotelServiceImpl implements HotelService {

    @Autowired
    private HotelRepository hotelRepository;


    @Transactional
    @Compensable(compensationMethod = "cancel")
    @Override
    public void order(HotelBooking booking) {
        if (booking.getAmount() > 2) {
            throw new IllegalArgumentException("can not order the rooms large than two");
        }
        booking.setId(null);
        booking.confirm();
        booking.setUuid(UUID.randomUUID().toString());
        hotelRepository.save(booking);
    }

    @Transactional
    @Override
    public void cancel(HotelBooking booking) {
        List<HotelBooking> hotelBookings = hotelRepository.findByUuid(booking.getUuid());
        if (hotelBookings != null && hotelBookings.size() > 0) {
            hotelRepository.deleteAll(hotelBookings);
        }
    }

    @Override
    public Collection<HotelBooking> getAllBookings() {
        return (Collection<HotelBooking>) hotelRepository.findAll();
    }

    @Override
    public void clearAllBookings() {
        hotelRepository.deleteAll();
    }

}
